package com.study.util;

import com.alibaba.fastjson.JSONArray;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.*;

/**
 * @version V1.0
 * @title: YouDaoUtil
 * @description: ${DESCRIPTION}
 * @author: wanghuilong
 * @date: 2019-04-23 16:42
 * @copyright: http://fingo.com.my/
 */
public class YouDaoUtil {

    public static String startTranscationEN(String tempStr) {
        //System.out.println("YouDaoUtil startTranscation tempStr:"+tempStr);
        String appKey = "12703a9649558795";
        String query = tempStr;
        String salt = String.valueOf(System.currentTimeMillis());
        String from = "zh-CHS";
        String to = "EN";
        String sign = md5(appKey + query + salt + "BMbcqk6x0JQAfpMkOCWiZl3y3ljiOYTo");
        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);
        params.put("sign", sign);
        params.put("salt", salt);
        params.put("appKey", appKey);
        String requestForHttpRet = null;
        try {
            requestForHttpRet = requestForHttp("http://openapi.youdao.com/api", params);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return requestForHttpRet;
    }

    public static String startTranscationCN(String tempStr) {
        //System.out.println("YouDaoUtil startTranscation tempStr:"+tempStr);
        String appKey = "12703a9649558795";
        String query = tempStr;
        String salt = String.valueOf(System.currentTimeMillis());
        String from = "EN";
        String to = "zh-CHS";
        String sign = md5(appKey + query + salt + "BMbcqk6x0JQAfpMkOCWiZl3y3ljiOYTo");
        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);
        params.put("sign", sign);
        params.put("salt", salt);
        params.put("appKey", appKey);
        String requestForHttpRet = null;
        try {
            requestForHttpRet = requestForHttp("http://openapi.youdao.com/api", params);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return requestForHttpRet;
    }

    public static String startTranscation(String tempStr) {
        //System.out.println("YouDaoUtil startTranscation tempStr:"+tempStr);
        String appKey = "12703a9649558795";
        String query = tempStr;
        String salt = String.valueOf(System.currentTimeMillis());
        String from = "zh-CHS";
        String to = "EN";
        String sign = md5(appKey + query + salt + "BMbcqk6x0JQAfpMkOCWiZl3y3ljiOYTo");
        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);
        params.put("sign", sign);
        params.put("salt", salt);
        params.put("appKey", appKey);
        String requestForHttpRet = null;
        try {
            requestForHttpRet = requestForHttp("http://openapi.youdao.com/api", params);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return requestForHttpRet;
    }

    public static String requestForHttp(String url, Map<String, String> requestParams) throws Exception {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        /**HttpPost*/
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        Iterator<Map.Entry<String, String>> it = requestParams.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> en = it.next();
            String key = en.getKey();
            String value = en.getValue();
            if (value != null) {
                params.add(new BasicNameValuePair(key, value));
            }
        }
        httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        /**HttpResponse*/
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        try {
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity, "utf-8");
            EntityUtils.consume(httpEntity);
        } finally {
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //System.out.println(result);
        //取出返回的json，并从其中精确的取出key为"translation"的值，最后返回
        com.alibaba.fastjson.JSONObject object = JSONArray.parseObject(result);
        JSONArray object2 = (JSONArray) object.get("translation");
        return object2.get(0).toString().toLowerCase().replaceAll("\\.", "");
    }

    /**
     * 生成32位MD5摘要
     *
     * @param string
     * @return
     */
    public static String md5(String string) {
        if (string == null) {
            return null;
        }
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'A', 'B', 'C', 'D', 'E', 'F'};

        try {
            byte[] btInput = string.getBytes("utf-8");
            /** 获得MD5摘要算法的 MessageDigest 对象 */
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            /** 使用指定的字节更新摘要 */
            mdInst.update(btInput);
            /** 获得密文 */
            byte[] md = mdInst.digest();
            /** 把密文转换成十六进制的字符串形式 */
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }
}
